package org.jeecg.modules.order.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.MinioUtil;
import org.jeecg.modules.chanp.entity.KuybChanp;
import org.jeecg.modules.electronicSeal.service.ElectronicSealService;
import org.jeecg.modules.order.entity.KuybOrder;
import org.jeecg.modules.order.entity.KuybOrderPayment;
import org.jeecg.modules.order.entity.KuybOrderPolicy;
import org.jeecg.modules.order.entity.KuybOrderChanp;
import org.jeecg.modules.order.mapper.KuybOrderPaymentMapper;
import org.jeecg.modules.order.mapper.KuybOrderPolicyMapper;
import org.jeecg.modules.order.mapper.KuybOrderChanpMapper;
import org.jeecg.modules.order.mapper.KuybOrderMapper;
import org.jeecg.modules.order.service.IKuybOrderService;
import org.jeecg.modules.orderShenh.entity.KuybOrderShenh;
import org.jeecg.modules.orderShenh.service.IKuybOrderShenhService;
import org.jeecg.modules.system.util.ConvertUpMoney;
import org.jeecg.modules.weixin.service.SubscribeMessageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.print.DocFlavor;
import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 订单
 * @Author: jeecg-boot
 * @Date: 2021-09-09
 * @Version: V1.0
 */
@Slf4j
@Service
public class KuybOrderServiceImpl extends ServiceImpl<KuybOrderMapper, KuybOrder> implements IKuybOrderService {
    @Autowired
    SubscribeMessageService subscribeMessageService;
    @Autowired
    IKuybOrderShenhService kuybOrderShenhService;
    @Autowired
    private KuybOrderMapper kuybOrderMapper;
    @Autowired
    private KuybOrderPaymentMapper kuybOrderPaymentMapper;
    @Autowired
    private KuybOrderPolicyMapper kuybOrderPolicyMapper;
    @Autowired
    private KuybOrderChanpMapper kuybOrderChanpMapper;

    @Autowired
    ElectronicSealService sealService;

    @Value("${pdfPath.tmpPath}")
    String tmpPath;

    // 临时文件夹获取java system变量中的临时路径，在web项目中是容器的temp文件夹,如果直接运行是系统临时文件夹.
    private static final String FILE_PATH_TEMPLATE = System.getProperty("java.io.tmpdir") + "/tempdf/%s";

    @Override
    @Transactional
    public void saveMain(KuybOrder kuybOrder, List<KuybOrderPayment> kuybOrderPaymentList, List<KuybOrderPolicy> kuybOrderPolicyList, List<KuybOrderChanp> kuybOrderChanpList) {
        kuybOrderMapper.insert(kuybOrder);
        if (kuybOrderPaymentList != null && kuybOrderPaymentList.size() > 0) {
            for (KuybOrderPayment entity : kuybOrderPaymentList) {
                //外键设置
                entity.setZhubid(kuybOrder.getId());
                entity.setDingdbh(kuybOrder.getDingdbh());
                kuybOrderPaymentMapper.insert(entity);
            }
        }
        if (kuybOrderPolicyList != null && kuybOrderPolicyList.size() > 0) {
            for (KuybOrderPolicy entity : kuybOrderPolicyList) {
                //外键设置
                entity.setZhubid(kuybOrder.getId());
                entity.setDingdbh(kuybOrder.getDingdbh());
                entity.setBaodh("POLICY_" + DateUtil.format(new Date(), "yyyyMMdd") + String.format("_%06d", kuybOrderPolicyMapper.count() + 1));
                kuybOrderPolicyMapper.insert(entity);
            }
        }

        if (kuybOrderChanpList != null && kuybOrderChanpList.size() > 0) {
            for (KuybOrderChanp entity : kuybOrderChanpList) {
                //外键设置
                entity.setZhubid(kuybOrder.getId());
                entity.setDingdbh(kuybOrder.getDingdbh());
                kuybOrderChanpMapper.insert(entity);
            }
        }
    }

    @Override
    @Transactional
    public void updateMain(KuybOrder kuybOrder, List<KuybOrderPayment> kuybOrderPaymentList, List<KuybOrderPolicy> kuybOrderPolicyList, List<KuybOrderChanp> kuybOrderChanpList) {
        kuybOrderMapper.updateById(kuybOrder);

        //1.先删除子表数据
        kuybOrderPolicyMapper.deleteByMainId(kuybOrder.getId());
        kuybOrderChanpMapper.deleteByMainId(kuybOrder.getId());

        //2.子表数据重新插入
        if (kuybOrderPaymentList != null && kuybOrderPaymentList.size() > 0) {
            kuybOrderPaymentMapper.deleteByMainId(kuybOrder.getId());
            for (KuybOrderPayment entity : kuybOrderPaymentList) {
                //外键设置
                entity.setZhubid(kuybOrder.getId());
                kuybOrderPaymentMapper.insert(entity);
            }
        }
        if (kuybOrderPolicyList != null && kuybOrderPolicyList.size() > 0) {
            for (KuybOrderPolicy entity : kuybOrderPolicyList) {
                //外键设置
                entity.setZhubid(kuybOrder.getId());
                kuybOrderPolicyMapper.insert(entity);
            }
        }
        if (kuybOrderChanpList != null && kuybOrderChanpList.size() > 0) {
            for (KuybOrderChanp entity : kuybOrderChanpList) {
                //外键设置
                entity.setZhubid(kuybOrder.getId());
                kuybOrderChanpMapper.insert(entity);
            }
        }
    }

    @Override
    @Transactional
    public void delMain(String id) {
        kuybOrderPaymentMapper.deleteByMainId(id);
        kuybOrderPolicyMapper.deleteByMainId(id);
        kuybOrderChanpMapper.deleteByMainId(id);
        kuybOrderMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void delBatchMain(Collection<? extends Serializable> idList) {
        for (Serializable id : idList) {
            kuybOrderPaymentMapper.deleteByMainId(id.toString());
            kuybOrderPolicyMapper.deleteByMainId(id.toString());
            kuybOrderChanpMapper.deleteByMainId(id.toString());
            kuybOrderMapper.deleteById(id);
        }
    }

    @Override
    public void sendEmail(String orderId) {
        KuybOrder kuybOrder = this.getById(orderId);
        if (kuybOrder == null)
            throw new RuntimeException("没有查到对应的订单");

//		log.info("收件人邮箱: ", kuybOrder.get);
//
//		SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
////        simpleMailMessage.setFrom(from);
//		simpleMailMessage.setTo(to);
//		simpleMailMessage.setSubject("酷延保电子合同");
//		simpleMailMessage.setText(text);
//
//		log.info("准备发送邮件");
////        javaMailSender.send(simpleMailMessage);
//		log.info("邮件发送成功");
    }

    @Transactional
    @Override
    public Integer audit(String dingdbh, String auditStatus, String auditMemo) {
        KuybOrder kuybOrder = this.getOne(new LambdaQueryWrapper<KuybOrder>().eq(KuybOrder::getDingdbh, dingdbh), false);
        if (kuybOrder == null)
            return -1;

        kuybOrder.setShenhjg(auditStatus);
        if (!this.updateById(kuybOrder))
            return -2;

        KuybOrderShenh kuybOrderShenh = new KuybOrderShenh();
        kuybOrderShenh.setDingdbh(dingdbh);
        // 人工核保
        kuybOrderShenh.setShenhfs("2");
        kuybOrderShenh.setShenhjg(auditStatus);
        kuybOrderShenh.setWentsm(auditMemo);

        if (!kuybOrderShenhService.save(kuybOrderShenh))
            throw new RuntimeException("保存审核日志异常");

        // 模板消息
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode objectNode = objectMapper.createObjectNode();

        ObjectNode value = objectMapper.createObjectNode();
        value.put("value", kuybOrder.getDingdbh());
        objectNode.set("character_string4", value);

        value = objectMapper.createObjectNode();
        value.put("value", DateUtil.formatDateTime(kuybOrderShenh.getCreateTime()));
        objectNode.set("date2", value);

        value = objectMapper.createObjectNode();
        value.put("value", auditStatus.equals("2") ? "审核通过" : "已驳回");
        objectNode.set("phrase1", value);

        value = objectMapper.createObjectNode();
        value.put("value", auditMemo);
        objectNode.set("thing3", value);

        subscribeMessageService.send(kuybOrder.getOpenId(), "LWpG_Z7ky9l4qW5N9VaCcoVhlfuS18PY_q_MF3oIscw", objectNode);

        return 0;
    }



    public void getElectronicPolicy(String id,String userToken) throws Exception {
        KuybOrderPolicy orderPolicy=kuybOrderPolicyMapper.selectById(id);
        if(orderPolicy==null){
            throw new Exception("保单不存在");
        }
        KuybOrderChanp chanp=kuybOrderChanpMapper.selectOne(new QueryWrapper<KuybOrderChanp>().eq("zhubid",orderPolicy.getZhubid()));
        KuybOrderShenh orderShenh= kuybOrderShenhService.getOne(new QueryWrapper<KuybOrderShenh>().eq("dingdbh",orderPolicy.getDingdbh()).orderByDesc("create_time"), false);
        //获取文件流
        FileInputStream input = new FileInputStream(new File(tmpPath));
        PdfReader reader = new PdfReader(input);
//生成后的PDF
//		String pdfPath = "D:/test/new.pdf";
        String fileName=orderPolicy.getBaodh()==null ? System.currentTimeMillis()+".pdf":orderPolicy.getBaodh()+".pdf";

        File of = new File(FILE_PATH_TEMPLATE+fileName);
        if (!of.getParentFile().exists()) {
            of.getParentFile().mkdirs();
        }
//输出文件流
        FileOutputStream fos = new FileOutputStream(of);
        PdfStamper stamp = new PdfStamper(reader,fos);
        AcroFields form = stamp.getAcroFields();
//字体
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
//设置itext专用中文字体
        form.setFieldProperty("abc", "textfont", bfChinese, null);
//pdf文本域赋值
        form.setField("vipname",orderPolicy.getBeibxr());//会员姓名
        form.setField("vipphoneno",orderPolicy.getBeibxrlxdh());//会员手机号
        form.setField("vipadd",orderPolicy.getBeibxrdz());//会员地址
        form.setField("vipCarNo",orderPolicy.getBebxcph());//车牌号
        form.setField("vipVin",orderPolicy.getChejh());//车架号
        form.setField("fadongjihao",orderPolicy.getFadjh());//发动机号
        form.setField("pinpai",orderPolicy.getChelmc());//车辆名称
        form.setField("shiyongxingzhi",orderPolicy.getShiyxz()==null || orderPolicy.getShiyxz().equals("0")? "非营运":"营运");//使用性质
        form.setField("gouchejiage",orderPolicy.getPeifxe());//赔付限额
        form.setField("xingshilicheng",orderPolicy.getXingslc()+"");//行驶里程
        form.setField("yuanchangbaoxiu",orderPolicy.getZhengczb());//原厂保修期限
        form.setField("cheliangzhuce",orderPolicy.getChudrq());//初登日期
        //此处需要判断是否过保（原厂保修时间和里程先到者为准）

//        String dd= addDate(orderPolicy.getChudrq(),orderPolicy.getYuancbxnx()==0 ? 0: orderPolicy.getYuancbxnx());//获取保修结束日期
       /* if((orderPolicy.getYuancbxgls()==0 ? 100000: orderPolicy.getYuancbxgls())>orderPolicy.getXingslc() && DateUtils.getMillis()<DateUtils.getMillis(DateUtils.str2Date(dd +" 00:00:00",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")))) {
            form.setField("vipshengxiaolicheng", "");
        }else {*/
            //获取保修结束里程
            form.setField("vipshengxiaolicheng", orderPolicy.getHuiykslc());//会员生效里程--我们之前说了，这种还在保修期内的车不用计算服务开始里程，只需要把结束里程写上就行，原厂10万公里的我们再加6万公里，结束就是16万，开始那里空着就行
//        }
        form.setField("vipjieshulicheng",(orderPolicy.getHuiyjslc()));//会员结束里程
        form.setField("snian",orderPolicy.getQibrq());//保险起期 -年
        form.setField("enian",orderPolicy.getZhongbrq());//保险止期 -年
        form.setField("createdate", DateUtils.date2Str(orderPolicy.getCreateTime(),new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));//会员下单时间
        KuybOrder order=kuybOrderMapper.selectById(orderPolicy.getZhubid());
        form.setField("xiaoxiejiage",order.getDingdje()/100+" 元（大写："+ConvertUpMoney.toChinese(order.getDingdje()/100+"")+" ）。");//保费-小写
        form.setField("policyno",orderPolicy.getBaodh()+"");//保单号
        form.setField("vipservicename",chanp.getChanpmc());//购买服务名称
//        form.setField("daxiejiage", );//保费-大写
        form.setField("fuwuqueren", orderShenh==null ? DateUtils.date2Str(orderPolicy.getCreateTime(),new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")): DateUtils.date2Str(orderShenh.getCreateTime(),new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));//服务确认时间
// 关闭输出

        stamp.setFormFlattening(true);
        stamp.close();
        fos.close();
        input.close();

//        FileInputStream inp1=new FileInputStream(FILE_PATH_TEMPLATE+fileName);

        sealService.requestSign1(id,userToken,FILE_PATH_TEMPLATE+fileName);//调用电子签章
//        String url= MinioUtil.upload(inp1,fileName);
//        orderPolicy.setDianzbdxzdz(url);
//        kuybOrderPolicyMapper.updateById(orderPolicy);
//        System.out.println(url+"-----------");

    }

    public static String addDate(String date, int n) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cd = Calendar.getInstance();//获取一个Calendar对象
        try {
            cd.setTime(sdf.parse(date));//设置calendar日期
        } catch (ParseException e) {
            e.printStackTrace();
        }
        cd.add(Calendar.YEAR, n);//增加n年

        //另一种方法
        //Calendar curr = Calendar.getInstance();
        //curr.set(Calendar.MONTH,curr.get(Calendar.MONTH)+1); //增加一月
        //Date date=curr.getTime();


        return sdf.format(cd.getTime());
    }

}
